package com.haoshuang.zhouzhoubang.ui.page.shop.detail

import android.app.Application.getProcessName
import android.content.ContentValues
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.webkit.WebView
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityProductDetailsBinding
import com.haoshuang.zhouzhoubang.model.bean.GoodsSpecBean
import com.haoshuang.zhouzhoubang.model.bean.ShopDetail
import com.haoshuang.zhouzhoubang.model.bean.ShoppingBannerBean
import com.haoshuang.zhouzhoubang.ui.dialog.ChooseGoodsSpecDialog
import com.haoshuang.zhouzhoubang.ui.page.shop.car.ShopCarActivity
import com.haoshuang.zhouzhoubang.ui.page.shop.confirm.OrderQrActivity
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.ktx.fromJson
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger


/**
 *  商品详情界面
 */
class ProductDetailsActivity :
    BaseVMActivity<ProductDetailsViewModel, ActivityProductDetailsBinding>() {

    private var detailBean: ShopDetail? = null

    // 规格参数
    private var specBean: GoodsSpecBean? = null

    override fun initView(savedInstanceState: Bundle?) {
        binding.appBar.ivBack.clickWithTrigger { finish() }
        binding.appBar.tvTitle.text = "商品详情"



        binding.tvButton.clickWithTrigger {
            // 加入购物车
            XPopup.Builder(this)
                .asCustom(
                    ChooseGoodsSpecDialog(
                        this,
                        detailBean?.spec?.fromJson(),
                        detailBean
                    ) { specId, num ->
                        vm.getData2("productId" to ids, "uniqueId" to specId, "cartNum" to num)
                    })
                .show()

        }
        binding.icBuy.clickWithTrigger {
            if (stock == 0) {
                toast("库存不足")
                return@clickWithTrigger
            }
            XPopup.Builder(this)
                .asCustom(
                    ChooseGoodsSpecDialog(
                        this,
                        detailBean?.spec?.fromJson(),
                        detailBean
                    ) { specId, num ->
                        startPage<OrderQrActivity>("orderType" to 0, "productId" to ids.toString(), "specId" to specId, "num" to num)
                    })
                .show()

        }
        binding.tvIconName.clickWithTrigger {
            startPage<ShopCarActivity>()
        }


        initBanner()
    }

    var stock = 0
    override fun onRestart() {
        super.onRestart()
        vm.getData("id" to ids)
    }

    /**初始化Banner 设置点击事件以及内容加载框架*/
    private fun initBanner() {
        //设置xbanner的图片点击事件
        binding.banner.setOnItemClickListener { xBanner, model, view, position ->
            model as ShoppingBannerBean // 此处的model无法自动识别，因此需要手动将其转换成setBannerData的参数中的数据类型
            Log.e(ContentValues.TAG, "initBanner:setOnItemClickListener:${model} ")
        }
        //设置xbanner加载图片
        binding.banner.loadImage { xBanner, model, view, position ->
            model as ShoppingBannerBean // 此处的model无法自动识别，因此需要手动将其转换成setBannerData的参数中的数据类型
            //在此处使用图片加载框架Glide加载图片
            Glide.with(this@ProductDetailsActivity)
                .load(model.url)
                .placeholder(R.mipmap.default_image)
                .error(R.drawable.ic_launcher_background)
                .into(view as ImageView)
        }


    }


    var ids = 0
    override fun initData() {
        ids = intent.getIntExtra("ids", 0)
        vm.getData("id" to ids)
    }

    override fun startObserve() {
        vm.getData2.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("加入成功")
            }
        }
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    detailBean = it
                    specBean = it.spec.fromJson()
                    val bannerFreshData = mutableListOf<ShoppingBannerBean>()
                    for (i in it.slider_image.indices) bannerFreshData.add(
                        ShoppingBannerBean(
                            it.slider_image[i],
                            ""
                        )
                    )

                    //刷新数据之后，需要重新设置是否支持自动轮播，通过判断图片数据列表的大小来决定
                    binding.banner.setAutoPlayAble(bannerFreshData.size > 1)
                    binding.banner.setBannerData(bannerFreshData)
                    binding.apply {
                        tvjj.text = it.store_name
                        tvKd2.text = "销量" + it.sales
                        stock = it.stock
                        tvProductDetailsPrice.text = "¥${it.price}"
                        if (it.content != null) {
                            var settings = webView.getSettings();

                            settings.setJavaScriptEnabled(true);//支持JS

                            var js = "<script type=\"text/javascript\">" +

                                    "var imgs = document.getElementsByTagName('img');" + // 找到img标签

                                    "for(var i = 0; i<imgs.length; i++){" + // 逐个改变

                                    "imgs[i].style.width = '100%';" + // 宽度改为100%

                                    "imgs[i].style.height = 'auto';" +

                                    "}" +

                                    "</script>";

                            //  webView.loadData(it.content+js,"text/html; charset=UTF-8", null);

                            webView.loadDataWithBaseURL(
                                null,
                                it.content + js,
                                "text/html",
                                "utf-8",
                                null
                            );
                        }

                    }

                }
            }
        }
    }

}